<?php
/*
 Plugin Name: ReadThis
 Plugin URI: http://www.xorax.info/blog/readthis/
 Description: Add an audio speaker on your post thanks to ReadSpeaker. <a href="./edit.php?page=readthis.php">Go to admin Page</a>.
 Version: 0.9.0
 Author: XoraX
 Author URI: http://www.xorax.info

 * Licence:
 * =============================================================================
 * Copyright 2007  PANEL Martin email : xxorax@gmail.com website : http://www.
 * xorax.info
 * 
 * This work is licensed under a Creative Commons Attribution-Share Alike 3.0
 * License (http://creativecommons.org/licenses/by-sa/3.0/)
*/

if(!(function_exists('file_post2audio')
|| function_exists('file_audio2post')
|| function_exists('the_audio')
|| function_exists('get_the_audio')
|| function_exists('readthis_init')
|| function_exists('get_the_audio_url')
|| function_exists('get_the_audio_inline')
|| function_exists('readthis_meta')
|| function_exists('readthis_ongetfeed')
|| function_exists('readthis_content_filter')
|| function_exists('readthis_skip_feedburner')
)):

define('READTHIS_TPL_DIR',dirname(__FILE__).'/template/');

$readthis_opt = get_option('readthis_opt');
if(!is_array($readthis_opt)){
  $readthis_opt = array(
    'audiopath' => 'wp-content/audio/',
    'method2get'=> 'url',
    'tpl-select' => 'default',
    'tpl-method' => 'inline', // widget, widget+inline, none
  );
  add_option('readthis_opt', $readthis_opt);
}

function file_post2audio($name, $is_url = false, $must_exist = false){
  global $readthis_opt;
  if($must_exist && !file_exists(file_post2audio($name, false, false))) return false;
  
  $p = $is_url ? get_option('siteurl') : ABSPATH;
  return trailingslashit($p).trailingslashit($readthis_opt["audiopath"]).$name.'.mp3';
}

function file_audio2post($filename){
  $filename = substr($filename,strrpos($filename,'/'));
  return substr($filename,0,-4);
}

$readthis_opt['tpl-method'] = 'widget+inline';

add_action('init','readthis_init');

function readthis_init(){
  global $readthis_opt, $readthis_tpl;
  
  $inline = strpos($readthis_opt['tpl-method'],'inline') !== false;
  $widget = strpos($readthis_opt['tpl-method'],'widget') !== false;
  
  $tplselect = $readthis_opt['tpl-select'];
  //$tplselect = 'abstract';
  $tpl_class = 'readthis_template_'.$tplselect;
  $tpl_file = trailingslashit(READTHIS_TPL_DIR).$tplselect.'/'.$tplselect.'.php';
  
  $readthis_tpl = false;
  if(file_exists($tpl_file)){
    include_once($tpl_file);
    if(class_exists($tpl_class)){
      $readthis_tpl = new $tpl_class(get_option('siteurl').'/'.PLUGINDIR.'/readthis/template/'.$tplselect.'/',$inline, $widget);
    }
  }
  if(!$readthis_tpl) return false;
  

  if($inline) add_filter('the_content','get_the_audio_inline');
    
  if(!is_callable(array(&$readthis_tpl,'widget'))) return false;
  else register_sidebar_widget('readthis',array(&$readthis_tpl,'widget'),'widget_readthis');

  if(!is_callable(array(&$readthis_tpl,'widget_control'))) return false;
  else register_widget_control('readthis',array(&$readthis_tpl,'widget_control'));
  
  //register_widget_control('Plugins used Plugin', 'jfa_PluginsUsedPlugin_widget_control', 200, 100);
}


function get_the_audio_url ($updtime = false, $_post = null){
  global $post, $readthis_opt;
  if(empty($_post)) $_post = &$post;
  if(empty($_post)) return false;
  if($readthis_opt['method2get'] == 'url'){
    if(is_object($_post)) $id = $_post->ID;
    elseif(!is_numeric($_post)) return false;

    if($url = readthis_meta($id)){
      if(!$updtime) $url = $url['url'];
    }
  } else {
    if(is_object($_post)) $name = $_post->post_name;

    $url = file_post2audio($name, true, true);
    if($url && $updtime)
      $url = array(
        'upd' => filemtime(file_post2audio($name, false)),
        'url' => $url
      );
  }
  if($url && $updtime) $url['outdate'] = (mysql2date('U', $_post->post_modified) > $url['upd']);
  return ($url) ? $url : false;
}

function get_the_audio($fct='html_object',$params = array(), $tpl_name = false){
  global $post, $readthis_opt, $readthis_tpl;

  if(!empty($fct) && is_callable(array(&$readthis_tpl,$fct))){
    $a = call_user_func_array(array(&$readthis_tpl,$fct),$params);
    //$a['counter'] = $readthis_tpl->counter;
    return $a;
  } else return false;
}

function the_audio($fct='html_object',$params = array()){
  echo get_the_audio($fct,$params);
}

function get_the_audio_inline($content = ''){ //for filter 'the_content'
  if(is_feed()) return $content;
  global $post, $readthis_opt;
  $new_content = get_the_audio('inline',array($content)); 
  if(empty($new_content)) echo $content;
  else echo $new_content;
}

function readthis_meta($post_id, $value = null){
  $key = '_readthis_audio';
  $key = '_rd_audio';
  if($value === null){
    return get_post_meta($post_id, $key, true);
  } else {
    if(empty($value)){
      return delete_post_meta($post_id, $key);
    }
    if(!is_array($value)){
      $value = array('upd' =>time(), 'url' =>$value);
    }
    if(!update_post_meta($post_id, $key, $value))
      add_post_meta($post_id, $key, $value, true);
  }
}

if( !is_admin() ):

if(isset($_GET['rd_pass'])):
  
  function readthis_content_filter($c){
    $pattern = '#<(?:code|pre)[^>]*(?:lang\s*=["\']\s*([\w\-]+)\s*["\'][^>]*)?>(.+)</(?:code|pre)>#siU';
    //$pattern = '#<(?:code|pre)[^>]*>(.+)</(?:code|pre)>#siU';
    if(preg_match_all($pattern,$c,$matchs,PREG_SET_ORDER)){
      foreach($matchs as $m){
//        $codename = !empty($m[1]) ? ' '.$m[1] : '';
//        $say_code ='code'.$codename.":<br />\n".$m[2].$codename.".<br/>\n";
        $say_code = '<br/>'.$m[2].'<br/>';
        $c = str_replace($m[0], $say_code, $c);
      }
    }
    return preg_replace(
      array(
        "#</?(?:code|pre)[^>]*>#si",
        "#<img[^>]+/>#Usi",
        "#<a[^>]+>#Usi",
        "#</a>#"
      ),"",$c);
  }
  
  function readthis_ongetfeed (){
    if(!is_feed()) return;
    $admin_opt = get_option('readthis_opt_admin');
    if($_GET['rd_pass'] != $admin_opt['pass2get']) return;

    //next is add because when I call wp_cache_delete in readthis->get_posts_audio() method, maybe I would like the cache be really delete immediatly no?
    //but it's not deleted immediatly, it is deleted at the end of script and there is not fonction to delete cache in cache file actually... 
    $GLOBALS['wp_object_cache']->cache_enabled = false;
    
    $GLOBALS['more'] = 1;
    //$filter = (!is_array(get_option("readthis_post2get"))) ? 'post_limits' : 'post_where';  
    //add_filter($filter,"readthis_feed_post_selector");
    $emptyreturn = create_function('$x','return "";');
    
    remove_filter('the_content','convert_smilies');
    add_filter('the_content','readthis_content_filter',11);
    add_filter('the_content_rss','readthis_content_filter',11);
    
    //$getposts = get_option("readthis_posts2get");
    $getpost = &$admin_opt['posts2get'];
    
    add_filter('post_limits', $emptyreturn);
    add_filter('pre_option_rss_use_excerpt',$emptyreturn);
    
    if(!empty($getposts) && is_array($getposts) && count($getposts) ){
      add_filter('the_title_rss', $emptyreturn);
      add_filter('posts_where',create_function('$x','return " AND `ID` IN ('.implode(',',$getposts).') ";'),1);
      
      $admin_opt['posts2get'] = 'ok';
      update_option('readthis_opt_admin',$admin_opt);
    }
  }
  add_action('pre_get_posts','readthis_ongetfeed');


  //this is to skip feebburner plugin ( http://orderedlist.com/wordpress-plugins/feedburner-plugin/ )
  function readthis_skip_feedburner(){
    remove_action('template_redirect', 'ol_feed_redirect');
    remove_action('init','ol_check_url');
  }
  add_action('plugins_loaded','readthis_skip_feedburner');

endif; //end isset($_GET['rd_pass'])
    
else: // is_admin()

load_textdomain('readthis', dirname(__FILE__) . "/readthis-".get_locale().".mo");

require_once(dirname(__FILE__).'/xorax_wp_ajax/xorax_wp_ajax.class.php');
//require_once(dirname(__FILE__).'/readthis.class.php');

$x = new xorax_wp_ajax_v1('readthis',__FILE__);
add_action('dbx_post_sidebar',array(&$x->callclass, 'edit_box'));

endif; //end is_admin()
endif; //end function_exists
?>